<template>
    <div class="h-full flex flex-col bg-white">
        <el-scrollbar wrap-class=" flex-1" view-class=" p-5">
            <el-form
                :model="attendanceMachine"
                ref="formRef"
                size="large"
                label-width="120px"
            >
                <el-form-item
                    v-for="(machine, index) in attendanceMachine"
                    :key="machine.key"
                    :label="`#${index + 1} 设备：`"
                >
                    <el-row :gutter="20" class="flex-1">
                        <el-col :span="6">
                            <el-form-item
                                :prop="index + '.name'"
                                :rules="nameRules"
                            >
                                <el-input
                                    v-model="machine.name"
                                    placeholder="为设备起个名称"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                :prop="index + '.ip'"
                                :rules="ipRules"
                            >
                                <el-input
                                    v-model="machine.ip"
                                    placeholder="请输入该设备的ip"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6"
                            ><el-space>
                                <el-button
                                    type="danger"
                                    :icon="Delete"
                                    @click.prevent="removeMachine(machine)"
                                />
                            </el-space>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addMachine"
                        >新增设备</el-button
                    >
                    <el-button type="primary" @click="handleApply"
                        >保存</el-button
                    >
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </div>
</template>


<script setup>
import { ref, reactive, onMounted, onUnmounted, watchEffect, inject } from 'vue'
import { Delete, Check, Back } from '@element-plus/icons-vue'
import { validateUrl } from '@/utils/validate-fn'
import {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElScrollbar,
    ElMessage,
    ElSpace,
    ElSwitch,
    ElDialog,
    ElRow,
    ElCol
} from 'element-plus'

const formRef = ref()

/**
 * 更新
 */
const inited = inject('inited')

/**
 * 组件挂载时调用
 */
onMounted(() => {
    const machine = localStorage.getItem('machine')
    if (machine) {
        attendanceMachine.value = JSON.parse(machine)
        inject('inited').value = true
    }
})

/**
 * 服务
 */
const attendanceMachine = ref([
    { key: 1, name: '', ip: null },
    { key: 2, name: '', ip: null },
    { key: 3, name: '', ip: null }
])

/**
 *  提交形式
 * @param {*} formEl
 */
async function submitForm(formEl) {
    if (!formEl) return false
    const res = await formEl.validate((valid) => {
        if (!valid) {
            return false
        } else {
            return true
        }
    })
    return res
}

/**
 * 判断是否存在名称
 */
const nameRules = {
    validator: (rule, value, cb) => {
        if (!value) {
            cb('请输入设备名称')
        } else if (
            attendanceMachine.value.filter((item) => item.name === value)
                .length > 1
        ) {
            cb('该设备名称产生冲突 请检查')
        } else {
            cb()
        }
    },
    trigger: 'blur'
}

/**
 * 判断IP是否存在和冲突
 */
const ipRules = {
    validator: (rule, value, cb) => {
        if (!value) {
            cb('请输入设备ip')
        } else if (!validateUrl(value)) {
            cb('ip格式错误 请检查')
        } else if (
            attendanceMachine.value.filter((item) => item.ip === value).length >
            1
        ) {
            cb('该设备ip产生冲突 请检查')
        } else {
            cb()
        }
    },
    trigger: 'blur'
}

/**
 * 删除设备号
 * @param {*} item
 */
function removeMachine(item) {
    const index = attendanceMachine.value.indexOf(item)
    if (index !== -1) {
        attendanceMachine.value.splice(index, 1)
    }
}
/**
 * 添加设备
 */
function addMachine() {
    attendanceMachine.value.push({
        key: Date.now(),
        ip: null
    })
}
/**
 * 保存
 */
async function handleApply() {
    const res = await submitForm(formRef.value)
    if (res) {
        localStorage.setItem('machine', JSON.stringify(attendanceMachine.value))
        ElMessage({
            showClose: true,
            message: '设置成功',
            type: 'success'
        })
        inited.value = true
    } else {
        localStorage.removeItem('machine')
        ElMessage({
            showClose: true,
            message: '请完成所有设备的ip设置',
            type: 'warning',
            grouping: true
        })
        inited.value = false
        return false
    }
}
</script>